import datetime
from werkzeug.security import generate_password_hash, check_password_hash

from app.core.extensions import db


class CommissionLog(db.Model):
    __tablename__ = 'commission_log'

    id = db.Column(db.BigInteger, primary_key=True)
    order_id = db.Column(db.BigInteger, nullable=False)
    from_user_id = db.Column(db.BigInteger, nullable=False)
    to_user_id = db.Column(db.BigInteger, nullable=False)
    amount = db.Column(db.Numeric(10, 2), nullable=False)
    rate = db.Column(db.Numeric(5, 2), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    tenant_id = db.Column(db.Integer, nullable=True, comment='租户ID')
    def to_dict(self):
        return {
            "id": self.id,
            "order_id": self.order_id,
            "from_user_id": self.from_user_id,
            "to_user_id": self.to_user_id,
            "amount": float(self.amount),  # Decimal 转 float
            "rate": float(self.rate),
            "created_at": self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at else None,
            "tenant_id": self.tenant_id
        }


class WithdrawLog(db.Model):
    __tablename__ = 'withdraw_log'

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)

    user_id = db.Column(db.BigInteger, nullable=False, index=True, comment='申请用户ID')  # ✅ 索引1：用户ID

    amount = db.Column(db.Numeric(10, 2), nullable=False, comment='提现金额')

    status = db.Column(
        db.String(20),
        nullable=False,
        default='pending',
        index=True,  # ✅ 索引2：状态
        comment='提现状态（pending=待审核，approved=通过，paid=已打款，rejected=驳回）'
    )

    method = db.Column(db.String(50), default='wechat', comment='提现方式（微信、支付宝等）')
    account = db.Column(db.String(100), comment='提现账号信息')
    remark = db.Column(db.String(255), comment='管理员备注')

    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
    tenant_id = db.Column(db.Integer, nullable=True, comment='租户ID')
    def to_dict(self):
        return {
            "id": self.id,
            "user_id": self.user_id,
            "amount": float(self.amount),
            "status": self.status,
            "method": self.method,
            "account": self.account,
            "remark": self.remark,
            "created_at": self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            "updated_at": self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None,
            "tenant_id": self.tenant_id
        }